/* Macro Purpose: Creates a downsampled stack of images from all images in a dir
 *                (passed in as an arg) that match a certain img type.
 *                It does this by opening each img, downsampling them,
 *                and then saving them all as a zip'd stack.
 *                
 * Parameters (as one str): 1:Debug (boolean indicating if this macro should print status, etc)
 *                          2:Path of images dir.  3:Path to result dir  4:Result img name
 *                          5:Scale to downsample by (2 means downsample to 1/2 orig dimensions)
 */

argsStr = getArgument();  // try to get arg passed in by user
if(argsStr == "") {
	print("\nNo argument string passed to this Fiji macro. Exiting now.\n");
	exit;
}
debugIt = false;
// Print str if in Debug mode
function printD(str) { 
  if(debugIt) print(str);	
} // end function printD() /////
//////////////////////////////////////////////////////////////////////////////
/// CONSTANTS & PARAMS (most get overridden by passed-in vals) /////////////// 
arg_delimeter = "@"; // the delimeter used to seperate args in the single arg str passed in

file_extension_to_open = ".fits";

saveImgPath = "/home/jfrank3/www-home/imagerecon/Images/";
saveImgName = "stack_from_resampled_FITS.zip";
saveImgType = "ZIP";

scale = 4;  // the ratio to downsample by (scale=4 means resample to 1/4 size)
shouldBrighten = true;
//// end Constants & Params //////////////////////
//////////////////////////////////////////////////

argsArray = split(argsStr, arg_delimeter); // split str on delimeter
// Break out the appropriate params from the argArray
debugIt     = argsArray[0];
pathToImg   = argsArray[1];
saveImgPath = argsArray[2];
saveImgName = argsArray[3];
scale       = argsArray[4];

// Get a list of all files in dir
images_to_open = getFileList(pathToImg);
//filesInSourceDir = getFileList(pathToImg);

///// DEBUGGING STATEMENT ////
printD("\nYou passed into this macro args: "); 
for(i=0; i < argsArray.length; i++) {
	printD("\"" + argsArray[i] + "\"");
}

// Open all imgs
for( i = 0; i < images_to_open.length; i++ ) {
	if(endsWith(images_to_open[i], file_extension_to_open)) {
		open(pathToImg + images_to_open[i]);
	}
}

// Brighten images so resultant stack will be legible
if(shouldBrighten) {
	for( i = 0; i < images_to_open.length; i++ ) {
		if(endsWith(images_to_open[i], file_extension_to_open)) {
			selectWindow(images_to_open[i]);
			//run("Brightness/Contrast...");
			//setMinAndMax(1150, 3650);
			//call("ij.ImagePlus.setDefault16bitRange", 0);

			//run("Enhance Contrast", "saturated=0.35");
			//run("Enhance Contrast", "saturated=0.4 normalize");
		}
	}
}

// Downsample imgs (in prep of sending the stack to the client for previewing)
for( i = 0; i < images_to_open.length; i++ ) {
	if(endsWith(images_to_open[i], file_extension_to_open)) {
		selectWindow(images_to_open[i]);
		      //run("Resample", "factor=4 factor=4 factor=4");
		run("Resample", "factor=" + scale + " factor=" + scale + " factor=" + scale);
		// Brighten images AGAIN (since downsampling darkens them) so resultant stack will be legible
		//run("Enhance Contrast", "saturated=0.35");
		//run("Enhance Contrast", "saturated=0.4 normalize");
	}
}

// Create the stack from all open images - first close the orig (full-sized) img windows so we don't stack them
for( i = 0; i < images_to_open.length; i++ ) {
	if(endsWith(images_to_open[i], file_extension_to_open)) {
		selectWindow(images_to_open[i]);
		close();
	}
}
run("Images to Stack", "name=[] title=[] use keep");

//run("Next Slice [>]");
//run("Enhance Contrast", "saturated=0.4 normalize");

saveAs(saveImgType, saveImgPath + saveImgName);

printD("Macro finished saving resampled stack to: \"" + saveImgPath + saveImgName + "\"");
